package com.xc.quickstart.infrastructure.ds;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;


@Slf4j
@Aspect
@Order(-1)
@Component
public class DataSourceAspect {

    @Pointcut("execution(public * com.xc.quickstart..*.*(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        DataSource annotation = (DataSource) joinPoint.getSignature().getDeclaringType().getAnnotation(DataSource.class);
        DataSource methodDataSource = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(DataSource.class);
        if (!Objects.isNull(annotation) || !Objects.isNull(methodDataSource)) {
            DataSourceEnum dbModule = Optional.ofNullable(methodDataSource).orElse(annotation).value();
            DataSourceContext.setDataSourceType(dbModule.getModule());
        }
    }

    @After("pointcut()")
    public void after() {
        DataSourceContext.clearDataSourceType();
    }


}
